<template>
  <div class="p-4 group-management">
    <div class="searchBox">
      <a-form :model="formState" ref="searchFormRef" layout='inline'>
        <a-form-item name="groupName" label="组名称" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
          <a-input v-model:value="formState.groupName" placeholder="请输入组名称" allowClear />
        </a-form-item>
        <a-form-item name="groupCode" label="组编号" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
          <a-input v-model:value="formState.groupCode" placeholder="请输入组编号" allowClear />
        </a-form-item>
        <a-form-item name="createBy" label="创建人" :label-col="{  style: { width: '90px' } }"
          :wrapper-col="{  style: { width: '200px' } }">
          <a-input v-model:value="formState.createBy" placeholder="请输入创建人" allowClear />
        </a-form-item>
        <a-form-item>
          <a-button style="margin-right: 10px" type="primary" @click="onSearch">查询</a-button>
          <a-button @click="resetForm">重置</a-button>
        </a-form-item>
      </a-form>
    </div>
    <div class="middle-content">
      <BasicTable title="组管理" :columns="columns" :data-source="data" bordered @columns-change="handleColumnChange"
        :canResize="false" :loading="loading" :row-selection="rowSelection" :pagination="false">
        <template #labels="{record}">
          <span class="label" v-if="record.tag">
            {{groupTagList.filter(e => e.value == record.tag)[0]?.label}}
          </span>
        </template>
        <template #operation="{ record }">
          <span>
            <a @click="addGroupUsersAction(record)" style="color: #0960bd">新建用户</a>
            <a-divider type="vertical" />
            <a @click="editBindedUsersAction(record)" style="color: #0960bd">已有用户</a>
            <a-divider type="vertical" />
            <a @click="editGroupAction(record)" style="color: #0960bd">编辑</a>
            <a-divider type="vertical" />
            <a-popconfirm title="确定要删除吗？" ok-text="确定" cancel-text="取消" @confirm="deleteAction(record)"
              @cancel="cancel">
              <a style="color: #0960bd">删除</a>
            </a-popconfirm>
          </span>
        </template>

        <template #toolbar>
          <a-button type="primary" :loading="loading" @click="AddGroupAction" >
            <PlusOutlined />新建
          </a-button>
          <a-popconfirm title="确定要删除吗？" ok-text="确定" cancel-text="取消" @confirm="batchDeleteAction" @cancel="cancel"
            :disabled="!hasSelected">
            <a-button type="primary" :loading="loading" :disabled="!hasSelected"
              style="padding: 2px 10px; margin-right: 0">
              <DeleteOutlined />批量删除
            </a-button>
          </a-popconfirm>
        </template>
      </BasicTable>
      <div class="flex py-2 items-end justify-end pagination">
        <a-pagination show-size-changer show-quick-jumper :current="pg.page" :pageSize="pg.size" :total="pg.total"
          :show-total="(total) => `共${total}条`" @change="onPageChange" @showSizeChange="onShowSizeChange" />
      </div>
    </div>
    <!-- 组下绑定新用户弹窗 -->
    <AddUserToGroupModal ref='addUserToGroupModal' :defaultData='editInfo' v-model:visible="addUserToGroupModalVis"
      @success='addUserSuccess' />
    <!-- 组下已绑定用户弹窗 -->
    <UserBindedModal ref='userBindedModal' :defaultData='editInfo' v-model:visible='userBindedModalVis' />

    <!-- 新建组modal -->
    <AddGroupModal @success='addGroupSuccess' v-model:visible="agmVisible" :defaultData='editInfo'
      :groupTagList='groupTagList' />
  </div>
</template>
<script lang="ts">
import { defineComponent, computed, reactive, ref, UnwrapRef, Ref } from 'vue';
import { ColumnProps } from 'ant-design-vue/es/table/interface';
import { toRefs } from '@vueuse/core';
import { BasicTable } from '/@/components/Table';
import { Icon } from '/@/components/Icon'
import {
  Divider,
  Form,
  Input,
  Row,
  Col,
  Pagination,
  Select,
  Popconfirm,
  Modal,
  Button,
  RadioGroup,
  Radio,
  Tree,
  Table,
} from 'ant-design-vue';
import { useMessage } from '/@/hooks/web/useMessage';
import {
  PlusOutlined,
  DeleteOutlined,
  EditOutlined,
  DiffOutlined,
  PlusSquareOutlined,
  CheckOutlined,
} from '@ant-design/icons-vue';
import { queryGroupReq, deleteGroupReq } from '/@/api/group';
import AddUserToGroupModal from './AddUserToGroupModal.vue'
import AddGroupModal from './AddGroupModal.vue'
import UserBindedModal from './UserBindedModal.vue'
import { getDictData } from '/@/api/dict'

type Key = ColumnProps['key'];

interface FormState {
  groupName: string | undefined;
  groupCode: string | undefined;
  createBy: string;
}

export default defineComponent({
  components: {
    BasicTable,
    ADivider: Divider,
    AForm: Form,
    AFormItem: Form.Item,
    AInput: Input,
    ARow: Row,
    ACol: Col,
    APagination: Pagination,
    ASelect: Select,
    APopconfirm: Popconfirm,
    AModal: Modal,
    AButton: Button,
    ARadioGroup: RadioGroup,
    ARadio: Radio,
    ATree: Tree,
    ATable: Table,
    PlusOutlined,
    DeleteOutlined,
    EditOutlined,
    DiffOutlined,
    PlusSquareOutlined,
    CheckOutlined,
    AddUserToGroupModal,
    AddGroupModal,
    UserBindedModal,
  },

  setup() {
    const datas = reactive({
      columns: [
        { title: '组名称', dataIndex: 'groupName', key: 'username', width: 150 },
        { title: '组编号', dataIndex: 'groupCode', key: 'nickName', width: 150 },
        { title: '标签', dataIndex: 'tag', width: 150, slots: { customRender: 'labels' } },
        { title: '挂载默认人员', dataIndex: 'autoFlag', width: 120, align: 'center', customRender: ({ record }) => record.autoFlag == 0 ? '否' : '是' },
        { title: '创建人', dataIndex: 'createBy', width: 120, align: 'center', },
        { title: '更新人', dataIndex: 'updateBy', width: 120, align: 'center', },
        { title: '创建时间', dataIndex: 'createDate', key: 'createDate', width: 150, align: 'center', },
        { title: '更新时间', dataIndex: 'updateDate', key: 'updateDate', width: 150, align: 'center', },
        { title: '备注', dataIndex: 'remark', key: 'lockFlag', width: 200 },
        { title: '操作', dataIndex: 'operation', key: 'operation', fixed: 'right', width: 320, slots: { customRender: 'operation' },},
      ],
      data: [], // 表格数据
      pg: {
        page: 1,
        size: 10,
        total: 0,
      },
      userVisible: false, // 新建、编辑用户弹窗显隐
      editNameVisible: false, // 修改组名弹窗显隐
      editInfo: undefined,
      editInfoRules: {
        groupCode: [{ required: true, message: '请输入组编号', trigger: 'blur' }],
        groupName: [{ required: true, message: '请输入组名称', trigger: 'blur' }],
      },
      isEdit: false,
      myTreeKey: '',
      currentGroupId: '', //修改组名 组id
      addUserToGroupModal: null,
      userBindedModal: false,
      userBindedModalVis: false,
      addUserToGroupModalVis: false,
      agmVisible: false,
    });

    const formState: UnwrapRef<FormState> = reactive({
      groupName: '',
      groupCode: '',
      createBy: ''
    });

    const searchFormRef = ref();
    const { createMessage } = useMessage();
    // 接口
    const apis = {

      //条件查询用户组
      async queryGroupAction() {
        let { data, respCode, respMsg } = await queryGroupReq({
          startIndex: datas.pg.page,
          pageSize: datas.pg.size,
          groupName: formState.groupName || '',
          groupCode: formState.groupCode || '',
          groupType: 0,
          createBy: formState.createBy,
        });
        if (respCode != 200) {
          createMessage({
        message: respMsg,
        type: 'warning',
      });
          return;
        }
        datas.data = data.list || [];
        datas.pg.total = data.total || 0;
        state.selectedRowKeys = [];
        state.selectedRows = [];
      },

      async deleteGroup(p) {
        state.loading = true;
        let { respCode, respMsg } = await deleteGroupReq(p)
        state.loading = false;
        if (respCode != 200) {
          createMessage({
        message: respMsg,
        type: 'warning',
      });
          return;
        }
        createMessage({
        message: respMsg,
      });
        apis.queryGroupAction();
      }
    };


    const methods = {
      resetForm() {
        searchFormRef.value.resetFields();
        methods.onSearch();
      },

      onSearch() {
        methods.resetPg()
        apis.queryGroupAction();
      },

      resetPg() {
        datas.pg.page = 1;
        datas.pg.size = 10;
        datas.pg.total = 0;
      },

      // 页码切换
      onPageChange(current: number) {
        datas.pg.page = current;
        apis.queryGroupAction();
      },

      // pagesize改变
      onShowSizeChange(p: number, s: number) {
        datas.pg.page = p == 1 ? p : 1;;
        datas.pg.size = s;
        apis.queryGroupAction();
      },

      // 取消删除
      cancel(e: MouseEvent) {
        console.log(e);
        createMessage({
        message: '已取消删除',
        type: 'info',
      });
      },

      // 删除申请历史
      /**
       * @param {number} id
      */
      deleteAction(p) {
        apis.deleteGroup({ groupIds: [p.groupId] });
      },

      // 批量删除申请历史
      batchDeleteAction() {
        let ids = state.selectedRows.map(e => e.groupId);
        ids.length > 0 && apis.deleteGroup({ groupIds: [...ids] });
      },

    };

    const rowSelection = {
      onChange: (selectedRowKeys: Key[], selectedRows: any[]) => {
        state.selectedRowKeys = selectedRowKeys;
        state.selectedRows = selectedRows;
      },
    };

    const state = reactive<{
      selectedRowKeys: Key[];
      selectedRows: any[];
      loading: boolean;
    }>({
      selectedRowKeys: [], // Check here to configure the default column
      selectedRows: [],
      loading: false,
    });
    const hasSelected = computed(() => state.selectedRowKeys.length > 0);

    /**
     * @param {ColumnChangeParam[]} data
    */
    function handleColumnChange() {
      // console.log('ColumnChanged', data);
    }

    function addUserSuccess() {
      methods.onSearch();
    }

    // edit group info
    function editGroupAction(group) {
      datas.agmVisible = true;
      datas.editInfo = group;
    }

    function addGroupSuccess() {
      methods.onSearch();
    }
    function addGroupUsersAction(group) {
      datas.editInfo = group;
      datas.addUserToGroupModalVis = true;
    }
    function AddGroupAction() {
      datas.editInfo = undefined;
      datas.agmVisible = true;
    }
    function editBindedUsersAction(r) {
      datas.editInfo = r;
      datas.userBindedModalVis = true;
    }


    const groupTagList = ref([]) as Ref<Array<any>>;
    const getGroupTagsAction = async () => {
      const { respCode, data } = await getDictData({ dictCode: ' ziam_group_tag' })
      if (respCode == 200) {
        groupTagList.value = data.map(e => ({
          label: e.name,
          value: e.value,
        }));
        apis.queryGroupAction();
      }
    }
    getGroupTagsAction();

    return {
      searchFormRef,
      ...toRefs(datas),
      hasSelected,
      ...toRefs(state),
      handleColumnChange,
      rowSelection,
      formState,
      ...methods,
      labelCol: { span: 4 },
      wrapperCol: { span: 18 },
      editGroupAction,
      addUserSuccess,
      addGroupSuccess,
      addGroupUsersAction,
      AddGroupAction,
      editBindedUsersAction,
      groupTagList,
    };
  }
});
</script>

<style lang="less" scoped>
html[data-theme='light'] {
  .searchBox {
    background-color: #fff;
  }

  .middle-content {
    background-color: #fff;
  }
}

html[data-theme='dark'] {
  .searchBox {
    background-color: #000;
  }

  .middle-content {
    background-color: #000;
  }
}

.searchBox {
  margin-bottom: 20px;
  padding: 10px 10px 0;
}

:deep(.ant-table-thead > tr > th) {
  font-weight: bold;
}

:deep(.ant-table-selection-column) {
  padding: 0;
  width: 20px !important;
}

:deep(.ant-card-body) {
  padding: 10px 15px;
}

:deep(.ant-table-tbody > tr > td) {
  padding: 15px;
}

//调整head行属性
:deep(.ant-table-thead > tr > th) {
  padding: 15px;
}

:deep(.ant-form-item) {
  margin-bottom: 10px !important;
}

:deep(.label) {
  font-size: 12px;
  border: 1px solid rgb(58, 173, 68);
  background-color: rgba(58, 173, 68, 0.1);
  color: rgb(58, 173, 68);
  border-radius: 3px;
  padding: 4px 8px;
  margin-left: 25px;
}

.inTree {
  display: flex;
  justify-content: space-between;
}
</style>

<style lang="less">
.group-management {
  .middle-content {
    padding: 20px;
    height: calc(100vh - 80px - 2rem - 72px);
    overflow: auto;
  }
}

.ant-modal-close-x {
  width: 55px;
  line-height: 45px;
  height: 45px;
}

.addUserToGroupModal {
  .ant-modal-body {
    padding: 20px;
  }
}
</style>
